/********************************************************
 * All rights Reserved, Designed By Silence
 * @Title:  UARTMainActivity.java   
 * @Package com.UARTTest   
 * @version V1.0     
 * @date:   2013-12-31 上午12:37:56     
 * @author: 飞翔电子工作室   宋连博     
 * @Description:  存放主界面类
 ********************************************************/

package com.UARTTest;

import java.util.ArrayList;
import java.util.HashMap;

import ourtools.Cmd_GenSui;
import ourtools.MySurfaceView;
import Database.Global;
import Database.GoodsDetail;
import Database.SQLC;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.SlidingDrawer;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @ClassName: UARTMainActivity
 * @Description: 程序主界面类
 * @author 飞翔电子工作室 宋连博
 * @date 2014-3-18 下午7:48:38
 * 
 */
@SuppressLint("ShowToast")
@SuppressWarnings("deprecation")
public class UARTMainActivity extends FT311UARTInterface {

	private Spinner mSpinner;// 商品分类
	private ArrayAdapter<String> adapter;// 适配器

	private LinearLayout ly_map = null;// 用于显示地图

	private ArrayList<HashMap<String, Object>> listItem;
	private ArrayList<HashMap<String, Object>> listItem1;
	private ArrayList<HashMap<String, Object>> listItem2;
	private TextView TimeText = null;

	private AutoCompleteTextView mAutoCompleteTextView;// 自动补全的edittext
	private ListView list_test_01, list_test_02, list_test_03, search_list;// 商品列表
	private MySurfaceView mySurfaceView = null;
	private SlidingDrawer slidingDrawer;
	private long main_time = Global.time;

	private int listflag = 0;// 标记当前显示列表，用于返回按键
	private int listflag_count;// 第二层标记
	private float[] zuobiao;
	private String cmd_main = "";
	private int menu3 = 0;//
	private boolean reflag = true;
	private boolean bgensui=true;
	private StringBuffer usbBuffer = new StringBuffer();
	private Cmd_GenSui myGensui = new Cmd_GenSui();
	protected CharSequence sError;
	private Thread thTogether = null;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		allinit();// 初始化所有控件

		mySurfaceView = new MySurfaceView(this);
		ly_map.addView(mySurfaceView);// 显示地图

		ArrayAdapter<String> autoAdapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1, Global.getStringll(-1));// 物品总分类
		mAutoCompleteTextView.setAdapter(autoAdapter);
		// 生成适配器的Item和动态数组对应的元素
		SimpleAdapter listItemAdapter = new SimpleAdapter(this, listItem,
				R.layout.goods_type_list, new String[] { "ItemImage",
						"ItemTitle", "ItemTitle_01" }, new int[] {
						R.id.ItemImage, R.id.ItemTitle_01, R.id.ItemTitle_02 }); // 添加并且显示
		list_test_01.setAdapter(listItemAdapter);
		list_test_02.setVisibility(View.GONE);
		list_test_03.setVisibility(View.GONE);
		list_test_01.setOnItemClickListener(my_List_Listener_01); // 大类商品监听添加
		list_test_02.setOnItemClickListener(my_List_Listener_02);// 小类商品监听添加
		list_test_03.setOnItemClickListener(my_list_Listener_03);// 商品列表监听添加
		search_list.setOnItemClickListener(my_list_Listener_04);// 搜索商品列表监听添加

		new Thread(new Homethread()).start();
		TimeText = (TextView) findViewById(R.id.testview);
	}

	/********************************************************
	 * @Title: allinit
	 * @date 2013-12-30
	 * @Description: 初始化布局
	 * @param 无
	 * @return 无
	 ********************************************************/
	private void allinit() {// 初始化监听以及控件定义

		int getDrawID[] = { R.drawable.goods_type_00, R.drawable.goods_type_01,
				R.drawable.goods_type_02, R.drawable.goods_type_03,
				R.drawable.goods_type_04, R.drawable.goods_type_05,
				R.drawable.goods_type_06, R.drawable.goods_type_07 };
		ly_map = (LinearLayout) findViewById(R.id.ly_map);
		slidingDrawer = (SlidingDrawer) findViewById(R.id.slidingdrawer);
		mSpinner = (Spinner) findViewById(R.id.type_spinner);
		mAutoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.auto_editText);
		list_test_01 = (ListView) findViewById(R.id.listtest_01);
		list_test_02 = (ListView) findViewById(R.id.listtest_02);
		list_test_03 = (ListView) findViewById(R.id.listtest_03);
		search_list = (ListView) findViewById(R.id.search_list);

		listItem = new ArrayList<HashMap<String, Object>>();
		for (int i = 0; i < 7; i++) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("ItemImage", getDrawID[i]);
			map.put("ItemTitle", Global.getStringll(-1)[i]);// 标题一
			map.put("ItemTitle_01",
					Global.getStringll(i)[0] + "、" + Global.getStringll(i)[1]
							+ "、" + Global.getStringll(i)[2] + "...");// 标题二
			listItem.add(map);
		}

		MyListener listener = new MyListener();
		((Button) findViewById(R.id.qiehuan_btn)).setOnClickListener(listener);
		((Button) findViewById(R.id.search_button))
				.setOnClickListener(listener);
		((Button) findViewById(R.id.goods_all)).setOnClickListener(listener);
		((Button) findViewById(R.id.pay_btn)).setOnClickListener(listener);
		((ImageButton) findViewById(R.id.goods_back))
				.setOnClickListener(listener);
	}

	/*
	 * 商品大类监听函数
	 */
	private OnItemClickListener my_List_Listener_01 = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {

			listflag = 2;
			listflag_count = position;
			adapter = new ArrayAdapter<String>(UARTMainActivity.this,
					android.R.layout.simple_expandable_list_item_1,
					Global.getStringll(position));
			list_test_02.setAdapter(adapter);
			list_test_03.setVisibility(View.INVISIBLE);
			list_test_02.setVisibility(View.VISIBLE);
			((Button) findViewById(R.id.goods_all)).setText(Global
					.getStringll(-1)[position]);
			((ImageButton) findViewById(R.id.goods_back))
					.setVisibility(View.VISIBLE);
		}
	};
	/*
	 * 商品小类监听函数
	 */

	private OnItemClickListener my_List_Listener_02 = new OnItemClickListener() {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			listflag = 3;
			list_test_03.setVisibility(View.VISIBLE);
			ArrayList<GoodsDetail> mygood = SQLC
					.searchGoodsDetail_usetype(Global
							.getStringll(listflag_count)[position]);
			listItem1 = new ArrayList<HashMap<String, Object>>();
			for (int i = 0; i < mygood.size(); i++) {
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("goods_Image", mygood.get(i).getPic_id());
				map.put("goods_name", mygood.get(i).getName());
				map.put("goods_price", mygood.get(i).getPrice());
				listItem1.add(map);
			}
			SimpleAdapter newAdapter = new SimpleAdapter(UARTMainActivity.this,
					listItem1, R.layout.goods_list, new String[] {
							"goods_Image", "goods_name", "goods_price" },
					new int[] { R.id.goods_ItemImage, R.id.goods_Title_01,
							R.id.goods_Title_02 });
			list_test_03.setAdapter(newAdapter);
		}
	};
	/*
	 * 详细商品列表
	 */
	private OnItemClickListener my_list_Listener_03 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 在这添加商品选择监听事件，对应地图操作
			zuobiao = SQLC.findcoord(listItem1.get(arg2).get("goods_name")
					.toString());
			LayoutInflater.from(UARTMainActivity.this);
			new AlertDialog.Builder(UARTMainActivity.this)
					.setTitle("确认提示")
					.setMessage("确认到此商品处去?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mySurfaceView.changeGoal(zuobiao[0],
											zuobiao[1]);
								}
							}).setNegativeButton("取消", null).show();

		}
	};
	/*
	 * 搜索商品列表
	 */
	private OnItemClickListener my_list_Listener_04 = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
				long arg3) {
			// 在这添加商品选择监听事件，对应地图操作
			zuobiao = SQLC.findcoord(listItem2.get(arg2).get("goods_name")
					.toString());
			LayoutInflater.from(UARTMainActivity.this);
			new AlertDialog.Builder(UARTMainActivity.this)
					.setTitle("确认提示")
					.setMessage("确认到此商品处去?")
					.setPositiveButton("确定",
							new DialogInterface.OnClickListener() {
								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									mySurfaceView.changeGoal(zuobiao[0],
											zuobiao[1]);
								}
							}).setNegativeButton("取消", null).show();
		}
	};

	/**
	 * @Fields handler : 用于线程间通信
	 */
	@SuppressLint("HandlerLeak")
	public Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			byte[] usbdata = new byte[64];
			switch (msg.what) {
			case 1:// 回复
				usbdata = Global.mingling.getBytes();
				System.out.println("send mingling" + Global.mingling);
				int size = usbdata.length;
				SendData(size, usbdata);
				Toast.makeText(getApplicationContext(), Global.mingling, 300)
						.show();
				break;
			case 3:// RFID
				usbdata = ("$3#").getBytes();
				SendData(usbdata.length, usbdata);
				break;
			case 4:// 光电
				usbdata = ("$4#").getBytes();
				SendData(usbdata.length, usbdata);
				break;
			case 5:
				usbdata = ("$5#").getBytes();
				SendData(usbdata.length, usbdata);
				break;
			case 6:
				Toast.makeText(getApplicationContext(), sError, 300)
				.show();
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	@Override
	protected void onResume() {
		super.onResume();
		ResumeAccessory();
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		if (Global.m_db != null) {
			Global.m_db.close();
		}
		DestroyAccessory(true);
		android.os.Process.killProcess(android.os.Process.myPid());
		super.onDestroy();
	}

	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		String[] a = { "导购状态", "跟随状态" };
		menu.clear();
		menu.add(0, 1, 1, "speed");
		menu.add(0, 2, 2, "x_y");
		menu.add(0, 3, 3, a[menu3]);
		menu.add(0, 4, 4, "RFID初始坐标");
		return super.onPrepareOptionsMenu(menu);
	}

	/*
	 * (non-Javadoc) <p>Title: onOptionsItemSelected</p> <p>Description:
	 * 菜单条目选择方法</p>
	 * 
	 * @param item
	 * 
	 * @return boolean
	 * 
	 * @see android.app.Activity#onOptionsItemSelected(android.view.MenuItem)
	 */
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {// end
		switch (item.getItemId()) {
		case 1:
			setSpeed();
			break;
		case 2:
			setX_y();
			break;
		case 3:
			gensui();
			break;
		case 4:
			RFID();
			//new Thread(new RFIDthread()).start();
			break;
		default:
			break;
		}
		return true;
	}

	/********************************************************
	 * @Title: setX_y
	 * @date 2013-12-30
	 * @Description: 手动设置小车位置
	 * @param 无
	 * @return 无
	 ********************************************************/
	private void setX_y() {// end
		LayoutInflater factory = LayoutInflater.from(UARTMainActivity.this);
		new AlertDialog.Builder(UARTMainActivity.this).setTitle("input x_y")
				.setView(factory.inflate(R.layout.setx_y, null))
				.setPositiveButton("确定", new DisDialog(2))
				.setNegativeButton("取消", null).show();
	}

	private void setSpeed() {// end
		LayoutInflater factory = LayoutInflater.from(UARTMainActivity.this);
		new AlertDialog.Builder(UARTMainActivity.this).setTitle("input speed")
				.setView(factory.inflate(R.layout.setspeed, null))
				.setPositiveButton("确定", new DisDialog(1))
				.setNegativeButton("取消", null).show();
	}

	private void RFID() {
		bgensui=false;
		thTogether = new Thread(new RFIDthread());
		thTogether.start();
	}

	/********************************************************
	 * @ClassName: RFIDthread
	 * @Description: RFID读取线程
	 * @author: 飞翔电子工作室 宋连博
	 * @date: 2013-12-30 下午10:14:24
	 * 
	 ********************************************************/
	class RFIDthread implements Runnable {
		@Override
		public void run() {
			setXY_RFID();
			while (!Thread.interrupted()) {// 等待RFID
				long start = System.currentTimeMillis();
				//cmd_main="$3,E20206260E034910B7D7#";
				if(findRFID(cmd_main)){
					cmd_main="";
					break;
				}
				long end = System.currentTimeMillis();
				try {
					if (end - start < main_time) {
						Thread.sleep(main_time - (end - start));
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			Global.setxy = true;
		}
	
	}
	/********************************************************
	 * @Title: findRFID
	 * @date 2013-12-30
	 * @Description: 数据库查RFID
	 * @param temp
	 *            接收的信息
	 * @return boolean true收到RFID信息，false未收到
	 ********************************************************/
	private boolean findRFID(String temp) {// 数据库查RFID
		if (temp.length() >= 11) {
			if (temp.substring(0, 3).equals("$3,")) {// RFID信息,查找RFID对应坐标
				float Rx = 0, Ry = 0;// RFID坐标
				Rx = SQLC.searchRFID(temp)[0];
				Ry = SQLC.searchRFID(temp)[1];
				Global.startx = Rx;
				Global.starty = Ry;
				Global.changeZhuangtai(3);
				Global.setxy = true;
				return true;
			} else {
			}
		}
		return false;
	}

	/********************************************************
	 * @Title: setXY_RFID
	 * @date 2013-12-30
	 * @Description: 用RFID初始化位置
	 * @param 无
	 * @return 无
	 ********************************************************/
	private void setXY_RFID() {
		Global.startx = mySurfaceView.getCarX();
		Global.starty = mySurfaceView.getCarY();
		Message message = new Message();
		message.what = 3;
		handler.sendMessage(message);
	}

	private void gensui() {
		menu3 = 1 - menu3;//更新菜单状态
		if(thTogether==null){
			bgensui = true;
			thTogether= new Thread(new GensuiThread());
			thTogether.start();
		}else{
			bgensui = false;
			thTogether=null;
		}
	}

	private void ChangeGendui(){
			int carx = (int) mySurfaceView.getCarX();
			int cary = (int) mySurfaceView.getCarY();
			int goalx = carx, goaly = cary;
			switch (mySurfaceView.getFangxiang()) {// 0上 1下 2左 3右
			case 0:
				goalx = carx + myGensui.getX();
				goaly = cary - myGensui.getY();
				break;
			case 1:
				goalx = carx - myGensui.getX();
				goaly = cary + myGensui.getY();
				break;
			case 2:
				goalx = carx - myGensui.getY();
				goaly = cary - myGensui.getX();
				break;
			case 3:
				goalx = carx + myGensui.getY();
				goaly = cary + myGensui.getX();
				break;
			default:
				System.out.println("cannt get here! gensui mubiaoshezhi");
				break;
			}
			mySurfaceView.changeGoal(goalx, goaly);
	}

	class GensuiThread implements Runnable {

		Message message = new Message();
	
		@Override
		public void run() {
			message.what = 5;
			while (!Thread.interrupted()&&bgensui) {// 
				long start = System.currentTimeMillis();
				if(!myGensui.isnNeared()){
					 ChangeGendui();
					 myGensui=new Cmd_GenSui();
				}
				message.what = 5;
				UARTMainActivity.this.handler.sendMessage(message);
				long end = System.currentTimeMillis();
				try {
					if (end - start < 3000) {
						Thread.sleep(3000 - (end - start));
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
	/********************************************************
	 * @Title: createDB
	 * @date 2013-12-30
	 * @Description: 创建数据库
	 * @param 无
	 * @return 无
	 ********************************************************/
	public void createDB() {
		if (Global.m_db == null) {
			Global.m_db = openOrCreateDatabase("SQLiteDemo.db", MODE_PRIVATE,
					null);
		}
	}

	/********************************************************
	 * @Title: deleteDB
	 * @date 2013-12-30
	 * @Description: 关闭并删除数据库
	 * @param 设定文件
	 * @return void 返回类型
	 ********************************************************/
	public void deleteDB() {
		if (Global.m_db != null) {
			Global.m_db.close();
		}
		deleteDatabase("SQLiteDemo.db");
	}

	/********************************************************
	 * @ClassName: MyListener
	 * @Description: 案件监听类
	 * @author: 飞翔电子工作室 宋连博
	 * @date: 2013-12-30 下午10:15:47
	 * 
	 ********************************************************/
	class MyListener implements OnClickListener {
		@Override
		public void onClick(View v) {
			if (v.getId() == R.id.search_button) {
				CharSequence t = ((AutoCompleteTextView) findViewById(R.id.auto_editText))
						.getText();
				String fenlei = mSpinner.getSelectedItem().toString();
				ArrayList<GoodsDetail> mygood = SQLC.searchGoodsDetail(fenlei,
						t.toString());
				listItem2 = new ArrayList<HashMap<String, Object>>();
				for (int i = 0; i < mygood.size(); i++) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					map.put("goods_Image", mygood.get(i).getPic_id());
					map.put("goods_name", mygood.get(i).getName());
					map.put("goods_price", mygood.get(i).getPrice());
					listItem2.add(map);
				}
				SimpleAdapter newAdapter = new SimpleAdapter(
						UARTMainActivity.this, listItem2, R.layout.goods_list,
						new String[] { "goods_Image", "goods_name",
								"goods_price" }, new int[] {
								R.id.goods_ItemImage, R.id.goods_Title_01,
								R.id.goods_Title_02 });
				search_list.setAdapter(newAdapter);
			}
			if (v.getId() == R.id.goods_all && slidingDrawer.isOpened()) {
				slidingDrawer.animateClose();
			}
			if (v.getId() == R.id.qiehuan_btn) {
				byte[] usb = new byte[64];
				usb = "$1,0,0,000".getBytes();
				SendData(usb.length, usb);
			}
			if (v.getId() == R.id.pay_btn) {
				SetConfig((int) 9600, (byte) 8, (byte) 1, (byte) 0, (byte) 0);// 初始化端口
			}
			if (v.getId() == R.id.goods_back) {// listview层次返回
				if (listflag == 3) {
					list_test_03.setVisibility(View.INVISIBLE);
					listflag = 2;
				} else if (listflag == 2) {
					list_test_02.setVisibility(View.INVISIBLE);
					listflag = 1;//
					((Button) findViewById(R.id.goods_all)).setText("全部商品");
					((ImageButton) findViewById(R.id.goods_back))
							.setVisibility(View.INVISIBLE);
				}
			}
		}

	}

	/********************************************************
	 * @ClassName: Homethread
	 * @Description: 状态转换线程
	 * @author: 飞翔电子工作室 宋连博
	 * @date: 2013-12-30 下午10:14:55
	 * 
	 ********************************************************/
	class Homethread implements Runnable {
		long start = 0;
		long end = 0;
		String text = "";

		@Override
		public void run() {
			createDB();
			SQLC.databaseinit();
			SetConfig(9600, (byte) 8, (byte) 1, (byte) 0, (byte) 0);
			while (!Thread.interrupted()) {
				System.currentTimeMillis();
				Message message = new Message();
				if (Global.canSend()) {
					message.what = 1;// 回复命令
					UARTMainActivity.this.handler.sendMessage(message);
					Global.setsendswitch(false);
					cmd_main = "";
				}
				if (cmd_main.length() >= 3) {
					if (cmd_main.length() == 11 && cmd_main.equals("$1,0,0,000#")) {// 无状-->1
						Global.changeZhuangtai(1);
						Global.distance = 0;

						cmd_main = "";
					} else if (cmd_main.substring(0, 3).equals("$4,")) {// 接收距离
						
						Global.distance = Float.valueOf(cmd_main.substring(3, 6));
						cmd_main = "";
					} else if (cmd_main.substring(0, 3).equals("$1,")) {
						Global.changeZhuangtai(2);
						Global.distance = 0;
						cmd_main = "";
					} else if (cmd_main.substring(0, 3).equals("$5,")) {
						myGensui = new Cmd_GenSui(cmd_main);
						cmd_main = "";
					} else {
						sError="Connt get here_homethread!";
						message.what = 6;// 回复命令
						UARTMainActivity.this.handler.sendMessage(message);
						cmd_main="";
					}
				}
				System.currentTimeMillis();
				try {
					if (end - start < main_time) {
						Thread.sleep(main_time - (end - start));
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	/********************************************************
	 * @ClassName: DisDialogListener
	 * @Description: 用于对话框监听
	 * @author: 飞翔电子工作室 宋连博
	 * @date: 2013-12-30 下午10:15:15
	 * 
	 ********************************************************/
	class DisDialog implements DialogInterface.OnClickListener {// end
		int i = 0;

		public DisDialog(int i) {
			super();
			this.i = i;
		}

		@Override
		public void onClick(DialogInterface dialog, int which) {
			if (i == 1) {// setspeed
				AlertDialog ad = (AlertDialog) dialog;
				EditText speed = (EditText) ad.findViewById(R.id.setspeed);
				Global.speed = Float.valueOf(speed.getText().toString());
			}
			if (i == 2) {
				AlertDialog ad = (AlertDialog) dialog;
				EditText speed = (EditText) ad.findViewById(R.id.setx);
				Global.startx = Float.valueOf(speed.getText().toString());
				speed = (EditText) ad.findViewById(R.id.sety);
				Global.starty = Float.valueOf(speed.getText().toString());
				Global.setxy = true;
			}
		}

	}

	@Override
	protected void onDataReceived(final byte[] buffer, final int size) {
		runOnUiThread(new Runnable() {
			public void run() {
				boolean flag = false;
				String a = new String(buffer, 0, size);
				if (a.substring(0, 1).equals("$")) {
					reflag = false;
				}
				if (reflag == false) {
					usbBuffer.append(a);
					if (a.substring(a.length() - 1, a.length()).equals("#")) {
						flag = true;
						reflag = true;
					}
				}
				if (flag == true) {
					flag = false;
					cmd_main = new String(usbBuffer);
					usbBuffer.delete(0, usbBuffer.length());
					if (TimeText != null) {
						TimeText.append(cmd_main + "\n");
					}
				}
			}
		});
	}
}
